<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Crypt;
use DB;
class GoodsController extends Controller
{
	//显示列表
    public function add()
    {
    	$data = DB::table('category as c1') 
                -> select('c1.*', DB::raw("concat(c1.path,',',c1.id) as sortpath"))
                -> orderBy('sortpath')
                -> get();

        foreach ($data as $key => $value)
        {
            $num = substr_count($value -> path, ',');
            $str = str_repeat('|----', $num);
            $data[$key] -> name = $str.$value -> name;
        }
        return view('admin.goods.add', ['title' => '商品添加', 'data' => $data ]);
    }

    //执行添加

    public function doadd(Request $request)
    {
        $this -> validate($request,[
            'pic' => 'image|max:2048',
            ],[
            'pic.image' => '你必须传一张图片',
            'pic.max' => '最大2M' 
            ]);
    	
    	$data = $request -> except('_token');
        $data['gscl'] = 0;
        $data['gstatus'] = 0;
        // dd($data);
       
        $time = Date('Y-m-d H-i-s');
        $data['created_at'] = $time;
        $data['updated_at'] = $time;


        if($request -> hasFile('gpic'))
        {

            if($request -> file('gpic') -> isValid())
            {
                //处理头像
                //获取文件后缀

                $extension = $request -> file('gpic') -> getClientOriginalExtension();

                $filename = mt_rand(100000,999999999).'.'.$extension;

                $dir = './uploads/goods/';

         
                $request -> file('gpic') -> move($dir, $filename);
                $data['gpic'] = '/uploads/goods/'.$filename;

            }else
            {
                $data['gpic'] = '/uploads/goods/default.jpg';
            }

        }    


        

        $res = DB::table('goods')->insert($data);

            
    	if($res)
         {
          return redirect('/admin/goods/add') -> with(['info' => '添加成功']);
         }else
         {
          return back() -> with(['info' => '添加失败']);
         }
    }



    //浏览
    public function index(Request $request)
    {
        // $da = $request -> except('_token');
        $num = $request -> input('num',10);
        $keywords = $request -> input('keywords','');
        $data = DB::table('goods') -> where('gname','like','%'.$keywords.'%') -> paginate($num) ;
        
        $d = '';
        foreach($data as $row){
            $pid= $row -> pid;
            $d[$row ->gid ] = DB::table('category') -> where('id',$pid) -> first();
        }
        
        

        return view('admin.goods.index',['data' => $data ,'request' => $request -> all(), 'title' => '商品列表','d'=>$d]);
    }


    //改变gstatus
    public function changegstatus(Request $request)
    {     
        $arr = ['上架' => 0,'下架' => 1];
        $gid = $request -> gid;
        $status = $arr[$request->status];
       
        if($status == 0){
            $status = 1;

        }else
        {
            $status = 0;
        }
        // return $gid;
        // return $status;
        $res = DB::table('goods') -> where('gid',$gid) -> update(['gstatus'=>$status]);
        
        if($res)
        {
            return $status;
        }
    }


    //改变gname
    public function changegname(Request $request)
    {
        $gid = $request -> gid;
        $gname = $request -> gname;

        //根据传过来的参数去修改为此ID的name值
        $res = DB::table('goods') -> where('gid',$gid) -> update(['gname' => $gname]);

        //判断是否修改成功
        if($res)
        {
            return 1;
        }else
        {
            return 0;
        }

    }

    //删除
    public function delete($id)
    {
        $oldPic = DB::table('goods') -> where('gid',$id) -> first() -> gpic;

        $res = DB::table('goods') -> where('gid',$id) -> delete();

        if($res)
        {
          DB::table('goods') -> where('gid', $id) -> delete();
            if(!empty($oldPic))
              {
                  
                  if($oldPic != '/uploads/goods/default.jpg')
                 {
                      if(file_exists('.'.$oldPic))
                      {
                        unlink('.'.$oldPic);
                      }
                    
                 }
              }
         }   

      if($res)
         {
          return redirect('/admin/goods/index') -> with(['info' => '删除成功']);
         }else
         {
          return back() -> with(['info' => '删除失败']);
         }
    }


    //修改
    public function edit($id)
    {
        // dd($id);
        $data = DB::table('goods')
          -> where('gid',$id) 
          -> first();
        return view('admin.goods.edit',['title'=>'编辑商品','data'=>$data]);
    }

    //修改提交
    public function update(Request $request)
    {

            $gid = $request -> gid;
            // dd($gid); 
            $data = $request -> except('_token','gid','gpic');
            // dd($data);

            $ispic = '';
            if($request -> hasFile('gpic'))
            {

                  if($request -> file('gpic') -> isValid())
                  {
                        //处理头像
                        //获取文件后缀
                        $extension = $request -> file('gpic') -> getClientOriginalExtension();
                        // dd($extension);
                        $filename = mt_rand(100000,999999999).'.'.$extension;

                        $dir = './uploads/goods/';


                        $request -> file('gpic') -> move($dir, $filename);

                        $data['gpic'] = '/uploads/goods/'.$filename;
                        // dd($userInfoData['gpic']);
                        //获取原来的图片
                        $oldPic = DB::table('goods') -> where('gid',$gid) -> first() -> gpic;
                        
                        

                        //判断是不是默认值
                        if(!empty($oldPic))
                        {
                                  unlink('.'.$oldPic);  
                        }
                  }

            }
            $res = DB::table('goods') -> where('gid',$gid) -> update($data);

            if($res)
            {
                return redirect('/admin/goods/index') -> with(['info' => '修改成功']);
            }else
            {
                return back() -> with(['info' => '修改失败']);
            }
    }
    //添加商品详情
    public function add_info()
    {
       $data = DB::table('goods') ->select() -> get();
       return view('admin.goods.add_info',['title'=>'添加商品详情','data'=>$data]);
    }

    public function index_info(Request $request)
    {
       $data = $request -> except('_token');
       $res = DB::table('goods_info') -> insert(['pid' =>$data['id'],'article_content'=>$data['article_content']]);
       if($res)
            {
                return redirect('/admin/goods/add_info') -> with(['info' => '修改成功']);
            }else
            {
                return back() -> with(['info' => '修改失败']);
            }

    }


    public function goodsDoinfo($id)
    {   
        $name = '';
        $text = '';
        $name = DB::table('goods') ->where('gid',$id)->first() -> gname;
        $text = DB::table('goods_info') -> where('pid',$id) -> first();
        if($text == null)
        {
            $text = '你没有添加该商品的详情';
        }else
        {
            $text = DB::table('goods_info') -> where('pid',$id) -> first() -> article_content;
        }

        $data['name'] = $name;
        $data['text'] = $text;
        return view('admin.goods.goodsInfo',['title'=>'商品详情页','data'=>$data,'id'=>$id]);
    }

    public function goodsEditinfo($id)
    {
        $text = DB::table('goods_info') -> where('pid',$id) -> first() ->article_content;
        return view('admin.goods.textedit',['title'=>'修改商品详情','text'=>$text,'id'=>$id]);
    }

    public function goodsupdate(Request $request)
    {
        $text = $request -> except('_token');
        
        $res =  DB::table('goods_info') ->where('pid',$text['id']) ->update(['article_content'=>$text['article_content']]);
        if($res)
            {
                return redirect('/admin/goods/index') -> with(['info' => '修改成功']);
            }else
            {
                return back() -> with(['info' => '修改失败']);
            }
    }

    public function deletecom(Request $request)
    {
        $num = $request -> input('num',10);
        $keywords = $request -> input('keywords','');
        $data = DB::table('goods') -> where('gname','like','%'.$keywords.'%') -> paginate($num) ;
        
        $arr = DB::table('comment') -> select() -> get();

        


        $gnum = [];
        $list = [];
        foreach($arr as $row)
        {   
            $gnum[$row->id] = DB::table('goods') -> where('gid',$row->gid) -> first() -> gname;
            $list[$row->id] = $row ->comtext;
        }
        return view('admin.goods.deletecom',['data' => $data ,'request' => $request -> all(), 'title' => '删除评论管理','gnum'=>$gnum,'list'=>$list]);
    }

    public function deleteoop($id)
    {
       $res = DB::table('comment') ->where('id',$id) ->delete();
       if($res)
            {
                return redirect('/admin/goods/deletecom') -> with(['info' => '删除成功']);
            }else
            {
                return back() -> with(['info' => '删除失败']);
            }
    }



}

